import fs from 'fs';

// 分析OPUS帧数据
function analyzeOpusFrame(buffer) {
    console.log('=== OPUS帧分析 ===');
    console.log(`帧大小: ${buffer.length} 字节`);
    console.log(`前16字节: ${buffer.slice(0, Math.min(16, buffer.length)).toString('hex')}`);
    
    if (buffer.length < 1) {
        console.log('❌ 帧数据太短');
        return;
    }
    
    // 解析TOC字节
    const toc = buffer[0];
    const config = (toc >> 3) & 0x1F;
    const stereo = (toc >> 2) & 0x01;
    const frameType = toc & 0x3;
    
    console.log(`TOC字节: 0x${toc.toString(16).padStart(2, '0')}`);
    console.log(`配置: ${config} (对应帧大小: ${getFrameSize(config)} 样本)`);
    console.log(`立体声: ${stereo ? '是' : '否'}`);
    console.log(`帧类型: ${frameType}`);
    
    // 检查数据有效性
    const validRange = Array.from(buffer).every(b => b >= 0 && b <= 255);
    if (!validRange) {
        console.log('❌ 数据范围异常');
        return;
    }
    
    console.log('✅ 这可能是有效的OPUS帧数据');
}

// 根据config获取帧大小
function getFrameSize(config) {
    const frameSizes = [
        40, 80, 160, 320,   // config 0-3: 2.5ms, 5ms, 10ms, 20ms
        640, 960, 1280, 1600,  // config 4-7: 40ms, 60ms, 80ms, 100ms
        1920, 2240, 2560, 2880,  // config 8-11: 120ms, 140ms, 160ms, 180ms
        3200, 3520, 3840, 4160,  // config 12-15: 200ms, 220ms, 240ms, 260ms
        4480, 4800, 5120, 5440,  // config 16-19: 280ms, 300ms, 320ms, 340ms
        5760, 6080, 6400, 6720,  // config 20-23: 360ms, 380ms, 400ms, 420ms
        7040, 7360, 7680, 8000,  // config 24-27: 440ms, 460ms, 480ms, 500ms
        8320, 8640, 8960, 9280   // config 28-31: 520ms, 540ms, 560ms, 580ms
    ];
    
    return config < frameSizes.length ? frameSizes[config] : '未知';
}

// 分析OPUS文件
function analyzeOpusFile(filePath) {
    try {
        console.log(`\n=== 分析OPUS文件: ${filePath} ===`);
        const data = fs.readFileSync(filePath);
        
        // 检查文件头
        if (data.length < 25) {
            console.log('❌ 文件太小，不是有效的OPUS文件');
            return;
        }
        
        const opusHead = data.slice(0, 8).toString('ascii');
        if (opusHead !== 'OpusHead') {
            console.log('❌ 不是有效的OPUS文件头');
            return;
        }
        
        console.log('✅ 有效的OPUS文件头');
        
        // 解析文件头信息
        const version = data[8];
        const channels = data[9];
        const preSkip = data.readUInt16LE(10);
        const sampleRate = data.readUInt32LE(12);
        const outputGain = data.readUInt16LE(16);
        const channelMapping = data[18];
        const frameSize = data.readUInt16LE(19);
        const totalFrames = data.readUInt32LE(21);
        
        console.log(`版本: ${version}`);
        console.log(`通道数: ${channels}`);
        console.log(`预跳过样本数: ${preSkip}`);
        console.log(`采样率: ${sampleRate}Hz`);
        console.log(`输出增益: ${outputGain}`);
        console.log(`通道映射: ${channelMapping}`);
        console.log(`帧大小: ${frameSize} 样本`);
        console.log(`总帧数: ${totalFrames}`);
        
        // 分析前几个OPUS帧
        let offset = 25;
        const framesToAnalyze = Math.min(5, totalFrames);
        
        console.log(`\n=== 分析前 ${framesToAnalyze} 个OPUS帧 ===`);
        for (let i = 0; i < framesToAnalyze; i++) {
            if (offset + 4 > data.length) break;
            
            const frameLength = data.readUInt32LE(offset);
            offset += 4;
            
            if (offset + frameLength > data.length) break;
            
            const frameData = data.slice(offset, offset + frameLength);
            console.log(`\n帧 ${i + 1}:`);
            analyzeOpusFrame(frameData);
            
            offset += frameLength;
        }
        
    } catch (error) {
        console.error('分析文件失败:', error.message);
    }
}

// 主函数
function main() {
    const args = process.argv.slice(2);
    
    if (args.length === 0) {
        console.log('用法: node analyze_opus.js <opus文件路径>');
        return;
    }
    
    const filePath = args[0];
    if (!fs.existsSync(filePath)) {
        console.log('文件不存在:', filePath);
        return;
    }
    
    analyzeOpusFile(filePath);
}

main();
